package org.swingDemo.UI.panel;

import org.swingDemo.util.IconUtil;
import org.swingDemo.util.UIUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;

public class ImagePanel extends JPanel {

    private Image image;
    private String imageDesc;

    public ImagePanel() {
    }

    public ImagePanel(Image image, String imageDesc) {
        this();
        this.image = image;
        this.imageDesc = imageDesc;
        this.repaint();
    }

    public ImagePanel(File file) {
        this();
        this.updateImage(file);
    }

    public void updateImage(File file) {
        try {
            if (file == null) {
                this.image = null;
                this.imageDesc = "";
            } else {
                if (file.isDirectory()) {
                    this.image = IconUtil.FolderIcon.getImage();
                } else {
                    this.image = ImageIO.read(file);
                }
                this.imageDesc = file.getName();
            }
            repaint();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        final int panelWidth = getWidth();
        final int panelHeight = getHeight();

        // 填充背景色
        g.setColor(Color.gray);
        g.fillRect(0, 0, panelWidth, panelHeight);

        if (this.image != null) {
            // 计算缩放系数
            int imageWidth = image.getWidth(null);
            int imageHeight = image.getHeight(null);
            double widthScale = 1.0 * panelWidth / (double) imageWidth;
            double heightScale = 1.0 * (panelHeight - 20) / (double) imageHeight;
            double scale = Math.max(widthScale, heightScale);
            imageWidth = (int) (scale * (double) imageWidth);
            imageHeight = (int) (scale * (double) imageHeight);

            // 重绘图像
            int x = (panelWidth - imageWidth) / 2;
            g.drawImage(image, x, 0, imageWidth, imageHeight, null);

            // 绘制图像名称
            final double descWidth = g.getFontMetrics().getStringBounds(imageDesc, g).getWidth();
            x = (int) ((panelWidth - descWidth) / 2);
            g.setColor(Color.black);
            g.drawString(imageDesc, x, panelHeight - 5);
            g.setColor(Color.white);
            g.drawString(imageDesc, x, panelHeight - 5);
        } else {
            g.setColor(Color.black);
            g.drawString("不是图形文件", 30, 100);
        }
    }
}
